import { marked } from 'marked'
import hljs from 'highlight.js'
import DOMPurify from 'dompurify'

// 扩展 marked 的渲染器
const renderer = new marked.Renderer()

renderer.link = (href, title, text) => {
  //console.log("链接解析",href, title, text)
  return `<a href="${href.href}" target="_blank" rel="noopener noreferrer">${href.text}</a>`
}

export const initMarkdown = () => {
  marked.setOptions({
    renderer,
    highlight: (code, lang) => {
      const language = hljs.getLanguage(lang) ? lang : 'plaintext'
      return hljs.highlight(code, { language }).value
    },
    breaks: true,
    gfm: true,
    smartLists: true
  })
}

export const safeMarkdown = (raw) => {
  return DOMPurify.sanitize(
    marked.parse(raw),
    {
      ALLOWED_TAGS: [
        'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'strong', 'em', 'blockquote', 'code', 'pre',
        'ul', 'ol', 'li', 'a', 'img', 'hr', 'br',
        'table', 'thead', 'tbody', 'tr', 'th', 'td'
      ],
      ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'target']
    }
  )
}